<script setup>
import { onMounted, ref } from 'vue'
import { User, Lock, Monitor, Message } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { usePageColorStore } from '@/stores'
import { userGenerateEmailCodeService, userRegService } from '@/api/user'
import { ZlMessage } from '@/utils/message'
import loginLeftDarkImg from '@/assets/login-left-dark.png'
import loginLeftLightImg from '@/assets/login-left-light.png'

const router = useRouter()
const pageColorStore = usePageColorStore()

// 表单相关
const loginFormRef = ref()
const loginForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  emailCode: ''
})
// 整个表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.length < 9) {
          return callback(new Error('账号最少是 9 位数字或英文字符！'))
        }
        if (value.length > 20) {
          return callback(new Error('账号长度最长为 20 个字符。'))
        }
        const regex = /^[a-zA-Z0-9]+$/
        if (!regex.test(value)) {
          return callback(new Error('账号只能包含数字字符或英文字符。'))
        }
        return callback()
      }
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.length < 10) {
          return callback(new Error('密码长度最少为 10 个字符。'))
        }

        if (value.length > 20) {
          return callback(new Error('密码长度最长为 20 个字符。'))
        }

        // 创建正则表达式来匹配至少一个英文字符和一个数字字符
        const hasEnglishChar = /[a-zA-Z]/.test(value)
        const hasNumberChar = /[0-9]/.test(value)
        if (!(hasEnglishChar && hasNumberChar)) {
          return callback(new Error('密码最少包含一个英文字符和一个数字字符！'))
        }
        if (value.split(' ').length > 1 || value.trim() !== value) {
          return callback(new Error('密码不能包含空格字符.'))
        }
        callback()
      }
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value != loginForm.value.password) {
          callback(new Error('两次输入密码不一致！'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  emailCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailRegex.test(value)) {
          callback(new Error('请输入合法的邮箱！'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 注册
const login = async () => {
  await loginFormRef.value.validate()
  const res = await userRegService(loginForm.value)
  if (res.data.code === 200) {
    ZlMessage.success(res.data.msg)
    router.push('/login')
  } else if (res.data.code === 201) {
    ZlMessage.warning(res.data.msg)
  }
}

// 获取邮箱验证码
const getEmailCode = async () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(loginForm.value.email)) {
    ZlMessage.error('请输入合法邮箱!')
    return
  }
  const res = await userGenerateEmailCodeService(loginForm.value)
  ZlMessage.success(res.data.msg)
}

onMounted(() => {
  const windowHeight = window.innerHeight
  document.querySelector('.login-page').style.marginTop =
    (windowHeight - 500) / 2 + 'px'

  // 获取要淡入的元素
  const elementRight = document.querySelector('.right')
  const elementLeft = document.querySelector('.left')

  // 使用setTimeout来延迟设置透明度为1，以触发过渡效果
  setTimeout(function () {
    elementRight.style.opacity = '1'
    elementRight.style.transform = 'translate(0, 0)'
  }, 100) // 延迟100毫秒触发透明度改变，从而触发淡入效果
  setTimeout(function () {
    elementLeft.style.opacity = '1'
    elementLeft.style.transform = 'translate(0, 0)'
  }, 900)
})
</script>

<template>
  <el-row
    class="login-page"
    :class="{
      loginDark: pageColorStore.isDark,
      loginLight: !pageColorStore.isDark
    }"
  >
    <el-col
      :span="12"
      class="left"
      style="display: flex; align-items: center; justify-content: center"
    >
      <img
        :src="pageColorStore.isDark ? loginLeftDarkImg : loginLeftLightImg"
        alt=""
        width="50%"
      />
    </el-col>
    <el-col :span="12" class="right">
      <div class="logo-box">
        <zlcode-h2>Register —— Page</zlcode-h2>
      </div>
      <null-box size="20"></null-box>

      <el-form
        @keydown.enter="login()"
        :model="loginForm"
        ref="loginFormRef"
        label-width="auto"
        label-position="left"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            :prefix-icon="User"
            placeholder="用户名"
            size="large"
            autocomplete="new-password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            :prefix-icon="Lock"
            size="large"
            placeholder="密码"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            type="password"
            :prefix-icon="Lock"
            size="large"
            placeholder="确认密码"
            v-model="loginForm.confirmPassword"
          ></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-row
          style="width: 100%; display: flex; justify-content: space-between"
        >
          <el-form-item prop="email">
            <el-input
              v-model="loginForm.email"
              size="large"
              :prefix-icon="Message"
              placeholder="邮箱"
              autocomplete="new-password"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="emailCode">
            <el-input
              v-model="loginForm.emailCode"
              size="large"
              :prefix-icon="Monitor"
              placeholder="验证码"
              style="width: 100px"
              autocomplete="new-password"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              style="border-radius: 15px; height: 38px"
              @click="getEmailCode"
              >获取验证码</el-button
            >
          </el-form-item>
        </el-row>

        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%; height: 45px; font-size: 18px"
            @click="login"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<style lang="scss" scoped>
.loginDark {
  background-image: linear-gradient(to right, #434343 0%, black 100%);
}
.loginLight {
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
.login-page {
  width: 1000px;
  height: 500px;
  margin: 0 auto;
  overflow: hidden;
  border-radius: 20px;
  box-shadow: 0 0 38px 10px rgba(0, 0, 0, 0.1);
  .left {
    // background: url('@/assets/login-left.png') no-repeat center / cover;
    opacity: 0;
    transform: translate(-250px, 0);
    /* transition: all 1s; */
    transition:
      transform 1s,
      opacity 2s;
    overflow: hidden;
  }
  .right {
    padding: 20px;
    transform: translate(0, -60px);
    opacity: 0;
    /* 初始透明度为0 */
    transition:
      transform 1s,
      opacity 2s;
    .logo-box {
      padding-top: 50px;
      display: flex;
      justify-content: center;
      img {
        width: 90%;
      }
    }
  }

  /*搜索input框 */
  :deep(.el-input__wrapper) {
    border-radius: 15px;
  }

  :deep(.el-button) {
    border-radius: 15px;
    border: none;
  }

  :deep(.arco-image-img) {
    margin-left: 5%;
    cursor: pointer;
    width: 93%;
    border-radius: 10px;
  }
}
</style>
